using CGF;
using LitJson;
using UnityEngine;
using UnityEngine.UI;

public class LoginUIEmail : MonoBehaviour
{
    public InputField inputNumber, inputCode, inputInviteCode;
    public CButton btnSendCode;

    private const string InputCacheKey = "InputEmail";

    private void Awake()
    {
        inputNumber.text = PlayerPrefs.GetString(InputCacheKey);
    }

    private void OnEnable()
    {
        BtnSendCode btn = btnSendCode.GetComponent<BtnSendCode>();
        if (btn) Destroy(btn);
        btnSendCode.gameObject.AddComponent<BtnSendEmailCode>();
        btnSendCode.SetClick(SendCode);
    }

    private async void SendCode()
    {
        if (!StringHelper.IsEmail(inputNumber.text))
        {
            Dialog.Alert(RootComponent.instance.GetComponent<LoginUI>().I18N_please_input_valid_email);
            return;
        }

        JsonData data = new JsonData();
        data["email"] = inputNumber.text;
        Network.Res res = await Network.Post("/v1/reward/oauth/code/mail", data);
        if (res.success)
        {
            Dialog.Alert(CommAssets.instance.I18N_sent_success);
            btnSendCode.GetComponent<BtnSendCode>().StartTimer();
        }
    }

    public async void Login()
    {
        if (!StringHelper.IsEmail(inputNumber.text))
        {
            Dialog.Alert(RootComponent.instance.GetComponent<LoginUI>().I18N_please_input_valid_email);
            return;
        }

        if (string.IsNullOrWhiteSpace(inputCode.text))
        {
            Dialog.Alert(RootComponent.instance.GetComponent<LoginUI>().I18N_please_input_email_code);
            return;
        }
        PlayerPrefs.SetString(InputCacheKey, inputNumber.text);

        JsonData data = new JsonData();
        data["email"] = inputNumber.text;
        data["code"] = inputCode.text;
        data["invite_code"] = inputInviteCode.text;
        Network.Res res = await Network.Post("/v1/reward/oauth/login/mail", data);
        RootComponent.instance.GetComponent<LoginUI>().OnLogin(res.jsonData);
    }
}
